package com.kh.statistics.video.service.impl;

import com.alibaba.fastjson.JSON;
import com.kh.statistics.video.constant.AccountsConstant;
import com.kh.statistics.video.core.MediaContext;
import com.kh.statistics.video.core.Platform;
import com.kh.statistics.video.core.login.MyCookie;
import com.kh.statistics.video.entity.Accounts;
import com.kh.statistics.video.entity.StatisticsMeta;
import com.kh.statistics.video.entity.StatisticsReq;
import com.kh.statistics.video.entity.VideoAccountsLogin;
import com.kh.statistics.video.exception.BizException;
import com.kh.statistics.video.factory.PlatformFactory;
import com.kh.statistics.video.helper.CookieHelper;
import com.kh.statistics.video.service.VideoAccountsService;
import com.kh.statistics.video.service.VideoStatisticsService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.List;
import java.util.Objects;
import java.util.Set;

/**
 * @ClassName VideoStatisticsServiceImpl
 * @Description TODO
 * @Author konghong1
 * @Date 2024/5/7 21:56
 * @Version 1.0
 **/
@Service
@Slf4j
public class VideoStatisticsServiceImpl implements VideoStatisticsService {

    @Autowired
    private PlatformFactory platformFactory;

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    @Autowired
    private VideoAccountsService videoAccountsService;

    @Override
    public void statistics(StatisticsReq statisticsReq) {
        Platform platform = platformFactory.getPlatform(statisticsReq.getPlatform());
        MediaContext mediaContext = new MediaContext();
        platform.statistics(handler(statisticsReq, mediaContext));
    }

    @Override
    public void oneStatistics(StatisticsReq statisticsReq) {
        Platform platform = platformFactory.getPlatform(statisticsReq.getPlatform());
        MediaContext mediaContext = new MediaContext();
        platform.oneStatistics(handler(statisticsReq, mediaContext), mediaContext);
    }

    private List<StatisticsMeta> handler(StatisticsReq statisticsReq, MediaContext mediaContext) {
        List<StatisticsMeta> statisticsMetaList = statisticsReq.getStatisticsMetaList();
        //账号不为空可获取是否有登录，没有再走以下逻辑
        if (StringUtils.isBlank(statisticsReq.getCookie()) && StringUtils.isNotBlank(statisticsReq.getAccountsId())) {
            String accountsStr = redisTemplate.opsForValue().get(String.format(AccountsConstant.VIDEO_ACCOUNTS_LOGIN,
                    statisticsReq.getAccountsId() + "_" + statisticsReq.getPlatform()));
            //账户登录信息
            VideoAccountsLogin videoAccountsLogin = JSON.parseObject(accountsStr, VideoAccountsLogin.class);
            if (Objects.isNull(videoAccountsLogin)) {
                throw new BizException(500, "cookie 信息不能为空，可直接辅助cookies,也可选登录用户");
            }
            Accounts accounts = new Accounts();
            accounts.setId(statisticsReq.getAccountsId());
            List<Accounts> search = videoAccountsService.search(accounts);
            if (!CollectionUtils.isEmpty(search)) {
                Accounts accounts1 = search.get(0);
                mediaContext.setAccounts(accounts1);
                statisticsReq.setAccountName(accounts1.getName());
            }

            if (StringUtils.isNotBlank(videoAccountsLogin.getCookies())) {
                statisticsReq.setCookie(videoAccountsLogin.getCookies());
                mediaContext.setVideoAccountsLogin(videoAccountsLogin);
            } else {
                if (null == videoAccountsLogin.getCookieSet() || videoAccountsLogin.getCookieSet().isEmpty()) {
                    throw new BizException(500, "cookie 信息不能为空，可直接辅助cookies,也可选登录用户");
                }
                Set<MyCookie> cookieSet = videoAccountsLogin.getCookieSet();
                StringBuilder stringBuilder = new StringBuilder();
                for (MyCookie cookie : cookieSet) {
                    stringBuilder.append(cookie.getName())
                            .append("=")
                            .append(cookie.getValue())
                            .append(";");
                }
                String cookie = stringBuilder.toString();
                statisticsReq.setCookie(cookie);
            }
        }
        statisticsMetaList.forEach((item) -> {
            item.setHeaders(CookieHelper.handlerCookie(statisticsReq.getCookie(),
                    item.getHeaders(), item.getJsonHeader()));
            item.setAccountName(statisticsReq.getAccountName());

        });
        return statisticsMetaList;
    }
}
